package com.gxuwz.bignews.fragments;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView;
import androidx.appcompat.app.AlertDialog;
import com.gxuwz.bignews.R;
import com.gxuwz.bignews.model.entity.News;
import com.gxuwz.bignews.view.activity.NewsDetailActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;

public class HomeFragment extends Fragment {
    private RecyclerView rvNewsList;
    private NewsAdapter newsAdapter;
    private List<News> newsList = new ArrayList<>();
    private EditText etSearch;
    private Button btnSearch;
    private TabLayout tabNewsCategory;
    private ImageButton btnCustomCategory;
    private static final String API_KEY = "cb4e16f1adcff115fc792a51c6261c20";
    //284c099e2102d09a9e7f237ea46fbdc4
    //cb4e16f1adcff115fc792a51c6261c20
    // API KEY
    private static final String PREF_CATEGORY_SETTINGS = "news_category_settings";
    
    // 新闻分类，Map的key为接口参数，value为显示名称
    private static final Map<String, String> NEWS_CATEGORIES = new LinkedHashMap<String, String>() {{
        put("top", "头条(推荐)");
        put("guonei", "国内");
        put("yule", "娱乐");
        put("tiyu", "体育");
        put("junshi", "军事");
        put("keji", "科技");
        put("caijing", "财经");
        put("shishang", "时尚");
    }};

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        TextView tvTitle = view.findViewById(R.id.tv_title);
        etSearch = view.findViewById(R.id.et_search);
        btnSearch = view.findViewById(R.id.btn_search);
        btnCustomCategory = view.findViewById(R.id.btn_custom_category);
        rvNewsList = view.findViewById(R.id.rv_news_list);
        tabNewsCategory = view.findViewById(R.id.tab_news_category);

        tvTitle.setText("新闻头条");
        btnSearch.setOnClickListener(v -> {
            String keyword = etSearch.getText().toString().trim();
            fetchNews(keyword.isEmpty() ? "top" : keyword);
        });
        
        // 设置自定义分类按钮点击事件
        btnCustomCategory.setOnClickListener(v -> showCategorySettingsDialog());
        
        rvNewsList.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter(newsList, news -> {
            // 处理新闻点击事件，跳转到新闻详情页
            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
            intent.putExtra("uniquekey", news.getUniqueKey());
            startActivity(intent);
        });
        rvNewsList.setAdapter(newsAdapter);

        // 初始化新闻分类标签
        initNewsCategories();

        // 默认加载推荐新闻
        fetchNews("top");
        return view;
    }
    
    // 初始化新闻分类标签
    private void initNewsCategories() {
        // 清除所有标签
        tabNewsCategory.removeAllTabs();
        
        // 获取用户保存的分类设置
        Set<String> savedCategories = getSavedCategories();
        
        // 确保添加头条(推荐)作为第一个标签
        TabLayout.Tab topTab = tabNewsCategory.newTab();
        topTab.setText(NEWS_CATEGORIES.get("top"));
        topTab.setTag("top");
        tabNewsCategory.addTab(topTab);
        
        // 添加其他分类标签（只添加用户选择的分类，除了"top"因为已经添加了）
        for (Map.Entry<String, String> entry : NEWS_CATEGORIES.entrySet()) {
            // 跳过"top"，因为已经添加了
            if (entry.getKey().equals("top")) continue;
            
            // 如果savedCategories为空（首次使用）或者包含当前分类，则添加该标签
            if (savedCategories.isEmpty() || savedCategories.contains(entry.getKey())) {
                TabLayout.Tab tab = tabNewsCategory.newTab();
                tab.setText(entry.getValue());
                tab.setTag(entry.getKey()); // 将API参数存储在Tag中
                tabNewsCategory.addTab(tab);
            }
        }

        // 设置标签选择监听器
        tabNewsCategory.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String categoryType = (String) tab.getTag();
                fetchNews(categoryType);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                String categoryType = (String) tab.getTag();
                fetchNews(categoryType);
            }
        });
        
        // 默认选择第一个标签（头条）
        if (tabNewsCategory.getTabCount() > 0) {
            tabNewsCategory.getTabAt(0).select();
        }
    }
    
    // 显示自定义分类设置对话框
    private void showCategorySettingsDialog() {
        if (getContext() == null) return;
        
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("自定义新闻分类");
        
        // 创建对话框布局
        LinearLayout layout = new LinearLayout(getContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(50, 30, 50, 30);
        
        // 获取已保存的分类设置
        Set<String> savedCategories = getSavedCategories();
        
        // 添加提示文本
        TextView tvTip = new TextView(getContext());
        tvTip.setText("选择您感兴趣的新闻类型：");
        tvTip.setPadding(0, 0, 0, 20);
        layout.addView(tvTip);
        
        // 为每个分类创建一个CheckBox
        Map<String, CheckBox> checkBoxMap = new HashMap<>();
        for (Map.Entry<String, String> entry : NEWS_CATEGORIES.entrySet()) {
            CheckBox checkBox = new CheckBox(getContext());
            checkBox.setText(entry.getValue());
            checkBox.setTag(entry.getKey());
            
            // 如果是"top"(头条)，设为选中且禁用（不可取消）
            if (entry.getKey().equals("top")) {
                checkBox.setChecked(true);
                checkBox.setEnabled(false);
                TextView tvNote = new TextView(getContext());
                tvNote.setText("(必选项)");
                tvNote.setTextSize(12);
                tvNote.setPadding(10, 0, 0, 0);
                
                // 创建水平布局放置头条选项和提示文本
                LinearLayout topLayout = new LinearLayout(getContext());
                topLayout.setOrientation(LinearLayout.HORIZONTAL);
                topLayout.addView(checkBox);
                topLayout.addView(tvNote);
                layout.addView(topLayout);
                
                checkBoxMap.put(entry.getKey(), checkBox);
            } else {
                // 其他分类，如果savedCategories为空（首次使用）或者包含当前分类，则设为选中
                if (savedCategories.isEmpty() || savedCategories.contains(entry.getKey())) {
                    checkBox.setChecked(true);
                }
                layout.addView(checkBox);
                checkBoxMap.put(entry.getKey(), checkBox);
            }
        }
        
        builder.setView(layout);
        
        // 添加确认和取消按钮
        builder.setPositiveButton("确定", (dialog, which) -> {
            // 保存用户选择的分类
            Set<String> selectedCategories = new HashSet<>();
            // 始终添加"top"作为选项
            selectedCategories.add("top");
            
            for (Map.Entry<String, CheckBox> entry : checkBoxMap.entrySet()) {
                // 跳过"top"，因为已经添加了
                if (entry.getKey().equals("top")) continue;
                
                if (entry.getValue().isChecked()) {
                    selectedCategories.add(entry.getKey());
                }
            }
            
            // 保存用户选择
            saveCategories(selectedCategories);
            
            // 重新初始化分类标签
            initNewsCategories();
        });
        
        builder.setNegativeButton("取消", null);
        
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    
    // 获取保存的分类设置
    private Set<String> getSavedCategories() {
        if (getContext() == null) return new HashSet<>();
        
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREF_CATEGORY_SETTINGS, Context.MODE_PRIVATE);
        return sharedPreferences.getStringSet("selected_categories", new HashSet<>());
    }
    
    // 保存分类设置
    private void saveCategories(Set<String> categories) {
        if (getContext() == null) return;
        
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(PREF_CATEGORY_SETTINGS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet("selected_categories", categories);
        editor.apply();
    }

    private void fetchNews(String type) {
        new Thread(() -> {
            try {
                String apiUrl = "https://v.juhe.cn/toutiao/index?key=" + API_KEY + "&type=" + type;//api接口
                URL url = new URL(apiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    reader.close();
                    parseNewsJson(sb.toString());
                }
            } catch (Exception e) {
                Log.e("NewsApi", "error", e);
            }
        }).start();
    }

    private void parseNewsJson(String json) {
        try {
            JSONObject obj = new JSONObject(json);
            if (obj.getInt("error_code") == 0) {
                JSONObject result = obj.getJSONObject("result");
                JSONArray dataArr = result.getJSONArray("data");
                List<News> tempList = new ArrayList<>();
                for (int i = 0; i < dataArr.length(); i++) {
                    JSONObject item = dataArr.getJSONObject(i);
                    News news = new News(
                            item.optString("uniquekey"),
                            item.optString("title"),
                            item.optString("date"),
                            item.optString("category"),
                            item.optString("author_name"),
                            item.optString("url"),
                            item.optString("thumbnail_pic_s"),
                            item.optString("is_content")
                    );
                    tempList.add(news);
                }
                new Handler(Looper.getMainLooper()).post(() -> {
                    newsList.clear();
                    newsList.addAll(tempList);
                    newsAdapter.notifyDataSetChanged();
                });
            }
        } catch (Exception e) {
            Log.e("NewsParse", "error", e);
        }
    }

    // 定义新闻条目点击接口
    interface OnNewsItemClickListener {
        void onNewsClick(News news);
    }

    // 新闻列表适配器
    static class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
        private final List<News> newsList;
        private final OnNewsItemClickListener listener;

        NewsAdapter(List<News> newsList, OnNewsItemClickListener listener) { 
            this.newsList = newsList;
            this.listener = listener;
        }

        @NonNull
        @Override
        public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
            return new NewsViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
            News news = newsList.get(position);
            holder.tvTitle.setText(news.getTitle());
            holder.tvDate.setText(news.getDate());
            holder.tvSource.setText(news.getAuthorName());
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onNewsClick(news);
                }
            });
            
            // 加载图片，处理无图情况
            if (news.getThumbnailPic() != null && !news.getThumbnailPic().isEmpty()) {
                Glide.with(holder.ivThumb.getContext())
                        .load(news.getThumbnailPic())
                        .placeholder(R.drawable.ic_launcher_background)
                        .error(R.drawable.ic_launcher_background)
                        .into(holder.ivThumb);
                holder.ivThumb.setVisibility(View.VISIBLE);
            } else {
                holder.ivThumb.setImageResource(R.drawable.ic_launcher_background);
                holder.ivThumb.setVisibility(View.INVISIBLE);
            }
        }
        
        @Override
        public int getItemCount() { return newsList.size(); }
        
        static class NewsViewHolder extends RecyclerView.ViewHolder {
            TextView tvTitle, tvDate, tvSource;
            ImageView ivThumb;
            NewsViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_news_title);
                tvDate = itemView.findViewById(R.id.tv_news_date);
                tvSource = itemView.findViewById(R.id.tv_news_source);
                ivThumb = itemView.findViewById(R.id.iv_news_thumb);
            }
        }
    }
}